﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using S3.DataModel;
using S3.Properties;
using S3.Biz;
using S3.Common;

namespace S3
{
    public partial class ManageDesk : S3FormBase
    {
        private bool _isChanged;

        public ManageDesk()
        {
            InitializeComponent();
            InitConfig();
            LoadData();
        }

        private void InitConfig()
        {            
            txtKindOfMachine.Text = Constants.KindOfMachines;
            //var kindOfMachines = Constants.KindOfMachines.Split(',');
            //int index = -1;
            //foreach (var item in kindOfMachines)
            //{
            //    index = index + 1;
            //    cblKindOfMachines.Items.Add(item);
            //    cblKindOfMachines.SetItemChecked(index, true);
            //}
        }

        private void LoadData()
        {
            var manager = new TimingServiceConfigurationManager();
            //gridDeskGameConfig.DataSource = manager.GetAll();
            gridDeskControl.DataSource = manager.GetAll();
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            int qty = Convert.ToInt32(numQuantityOfMachine.Value);
            var list = new List<TimingServiceConfiguration>();
            string strPreName = txtPreName.Text.Trim() + " ";
            string strKindOfMachine = txtKindOfMachine.Text.Trim().TrimEnd(',');
            //foreach (var item in cblKindOfMachines.CheckedItems)
            //{
            //    strKindOfMachine = strKindOfMachine + item + ",";
            //}

            int quantity = Convert.ToString(qty).Length;
            for (int i = 1; i <= qty; i++)
            {
                string deskName = strPreName + GenerateZeroCharacter(quantity, Convert.ToString(i).Length) + i;

                var item = new TimingServiceConfiguration
                               {
                                   TimingServiceName = deskName,
                                   Types = strKindOfMachine,
                                   //Status = DeskStatusValue.Text[DeskStatus.Avaiable] + "",
                               };

                list.Add(item);
            }

            gridDeskControl.DataSource = list;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            DialogResult result =
                XtraMessageBox.Show("Viec nay co the se anh huong den du lieu cac may dang choi. Ban van muon luu?", "Chu y",
                                MessageBoxButtons.YesNo);
            if (result != DialogResult.Yes) return;

            string[] kindOfMachineRootList = txtKindOfMachine.Text.Trim().TrimEnd(',').Split(',');

            var listItems = new List<TimingServiceConfiguration>();
            for (int i = 0; i < gridViewDesk.RowCount; i++)
            {
                object deskName = gridViewDesk.GetRowCellValue(i, "TimingServiceName");
                object kindOfMachineList = gridViewDesk.GetRowCellValue(i, "KindOfMachineName");

                if (deskName == null && kindOfMachineList == null)
                    continue;

                string strDeskName = gridViewDesk.GetRowCellValue(i, "TimingServiceName").ToString().Trim();
                string strKindOfMachineList = gridViewDesk.GetRowCellValue(i, "KindOfMachineName").ToString().Trim();

                string[] kindOfMachinesCurrentList = strKindOfMachineList.Trim().TrimEnd(',').Split(',');
                foreach (string item in kindOfMachinesCurrentList)
                {
                    string kind = item.Trim();
                    if (!kindOfMachineRootList.Contains(kind))
                    {
                        XtraMessageBox.Show("Loại máy " + item + " của " + strDeskName +
                                        " không tồn tại trong danh sách gốc.");
                        gridViewDesk.SelectRow(i);
                        return;
                    }
                }

                string strStatus = DeskStatusValue.Text[DeskStatus.Avaiable];
                    // gridDeskGameConfig.Rows[i].Cells[2].Value + "";

                //Check

                if (!string.IsNullOrEmpty(strDeskName))
                {
                    //Save 

                    var item = new TimingServiceConfiguration
                                   {
                                       TimingServiceName = strDeskName.Trim(),
                                       Types = strKindOfMachineList,
                                       Status = strStatus
                                   };

                    //Add to list
                    listItems.Add(item);
                }
            }

            if (listItems.Count > 0)
            {
                using (var manager = new TimingServiceConfigurationManager())
                {
                    manager.Save(listItems);
                }

                Settings.Default.KindOfMachines = txtKindOfMachine.Text.Trim();
                Settings.Default.Save();
            }

            _isChanged = true;
            Close();
        }
   
        /// <summary>
        /// Close form if click ESC
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>

        private void ManageDesk_FormClosing(object sender, FormClosingEventArgs e)
        {
           // if (_isChanged) _ownerForm.ShowData();
        }

        #region ProcessCmdKey

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            try
            {
                if (msg.WParam.ToInt32() == (int) Keys.Escape)
                {
                    Close();
                }
                else
                {
                    return base.ProcessCmdKey(ref msg, keyData);
                }
            }
            catch (Exception Ex)
            {
                XtraMessageBox.Show("Key Overrided Events Error:" + Ex.Message);
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        #endregion

        #region Private methods

        private static string GenerateZeroCharacter(int intBig, int intSmall)
        {
            if (intSmall >= intBig)
            {
                return string.Empty;
            }
            else
            {
                var builder = new StringBuilder();
                for (int i = 0; i < intBig - intSmall; i++)
                {
                    builder.Append("0");
                }
                return builder.ToString();
            }
        }

        #endregion

        private void gridViewDesk_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                if (e.RowHandle >= 0)
                {
                    //Check duplicate service name
                    {
                        string strDeskName = gridViewDesk.GetRowCellValue(e.RowHandle, "TimingServiceName") + "";
                        string strKindOfMachineList = gridViewDesk.GetRowCellValue(e.RowHandle, "KindOfMachineName") + "";
                        string strStatus = gridViewDesk.GetRowCellValue(e.RowHandle, "Status") + "";

                        if (!string.IsNullOrEmpty(strDeskName) && !string.IsNullOrEmpty(strKindOfMachineList) &&
                            !string.IsNullOrEmpty(strStatus))
                        {
                            for (int i = 0; i < gridViewDesk.RowCount - 1; i++)
                            {
                                if (gridViewDesk.GetRowCellValue(i, "TimingServiceName") != null && i != e.RowHandle &&
                                    strDeskName.Trim().ToLower() ==
                                    gridViewDesk.GetRowCellValue(i, "TimingServiceName").ToString().ToLower())
                                {
                                    gridViewDesk.SetRowCellValue(e.RowHandle, "TimingServiceName", "");
                                    XtraMessageBox.Show("Trùng tên " + strDeskName);
                                    gridViewDesk.SelectRow(e.RowHandle);
                                    break;
                                }
                            }
                        }
                    }

                    if (!_isChanged)
                    {
                        _isChanged = true;
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }
    }
}